package ru.fivestarter.view.authorisation;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import com.octo.captcha.service.image.ImageCaptchaService;

public class CaptchaValidator implements Validator {
	public static final char[]     INVALID_CHARS                     = new char[] {'*', '@', '/', '\\'};
    public static final int        MAX_NAME_LENGTH                 = 50;

    public static final String     VALUEREQUIRED_ERROR_MESSAGE     = "Value is required.";
    public static final String     TEXTNOTNATCH_ERROR_MESSAGE         = "Text not match text on image";
	public CaptchaValidator() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void validate(FacesContext context, UIComponent component,
            Object value) throws ValidatorException {
        String val = ((String)value).trim();
        if (val.isEmpty()) {
            throw new ValidatorException(
                new FacesMessage(VALUEREQUIRED_ERROR_MESSAGE, VALUEREQUIRED_ERROR_MESSAGE)
            );
        }
        // в этом месте получаем ссылку на imageCaptchaService, что бы потом выполнить на нем проверку капчи
       // HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();
        ImageCaptchaService imageCaptchaService=(ImageCaptchaService) context.getApplication().getExpressionFactory().createValueExpression(context.getELContext(), "#{imageCaptchaService}", ImageCaptchaService.class).getValue(context.getELContext());
       /* WebApplicationContext appContext =
            WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
        assert appContext != null;
       
        ImageCaptchaService imageCaptchaService = (ImageCaptchaService)appContext.getBean("imageCaptchaService");       
*/
       
        if (!imageCaptchaService.validateResponseForID(RegisterController.CAPTCHA_ID, val)) {
            throw new ValidatorException(
                new FacesMessage(TEXTNOTNATCH_ERROR_MESSAGE, TEXTNOTNATCH_ERROR_MESSAGE));
        }
    }

}
